<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="increment">+</button>
  <span id="count">0</span>
  <button id="decrement">-</button>
  <script src="./middleware/logger.js"></script>
  <script src="./middleware/thunk.js"></script>
  <script src="./myRedux.js"></script>
  <script>
    // enhancer函数对dispatch函数进行增强
    function enhancer(createState) {
      return function(reducer, preloadedState) {
        // 这里只需要传递两个参数去创建store对象
        let store = new createState(reducer, preloadedState)
        let dispatch = store.dispatch
        // 增强dispatch函数,从而可以自定义处理一些操作(异步操作等...)
        function _dispatch(action) {
          if(typeof action === 'function'){
            return action(dispatch)
          }
          dispatch(action)
        }
        return {
          ...store,
          dispatch: _dispatch
        }
      }
    }

    const initialState = {
      counter: 0
    }
    // reducer函数
    const counterReducer = (state, action) => {
      switch(action.type) {
        case 'increment':
          return state + 1 
        case 'decrement':
          return state - 1
        default:
          return state
      }
    }

    const rootReducer = combineReducers({counter: counterReducer})
    // 创建store
    const store = new createStore(rootReducer, initialState, applyMiddleware(logger, thunk))

    // // 注册action actionCreator函数来创建
    // const incrementAction = { type: 'increment' }
    // const decrementAction = { type: 'decrement' }
    const increment = () => ({ type: 'increment'})
    const decrement = () => ({ type: 'decrement'})

    // 获取合并后的actions对象
    const actions = bindActionCreators({increment, decrement}, store.dispatch)

    document.getElementById('increment').addEventListener('click', () => {
      // 通过该方式可以触发异步操作
      // store.dispatch(dispatch => {
      //   setTimeout(() => {
      //     dispatch(incrementAction)
      //   }, 500)
      // })
      actions.increment()
    })
    document.getElementById('decrement').addEventListener('click', () => {
      actions.decrement()
    })

    store.subscribe(() => {
      document.getElementById('count').innerHTML = store.getState().counter
    })
  </script>
</body>
</html>